<template>
  <div class="system-config-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">系统配置</div>
      <div class="header-actions">
        <el-button @click="exportConfig">导出配置</el-button>
        <el-button @click="importConfig">导入配置</el-button>
        <el-button @click="resetConfig">重置配置</el-button>
        <el-button type="primary" @click="saveConfig">保存配置</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧导航 -->
      <el-col :span="6">
        <el-card shadow="hover" class="config-nav">
          <el-menu
            :default-active="activeMenu"
            class="config-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="basic">
              <i class="el-icon-setting"></i>
              <span>基础配置</span>
            </el-menu-item>
            <el-menu-item index="model">
              <i class="el-icon-data-analysis"></i>
              <span>模型配置</span>
            </el-menu-item>
            <el-menu-item index="prediction">
              <i class="el-icon-monitor"></i>
              <span>预测配置</span>
            </el-menu-item>
            <el-menu-item index="notification">
              <i class="el-icon-bell"></i>
              <span>通知配置</span>
            </el-menu-item>
            <el-menu-item index="backup">
              <i class="el-icon-document"></i>
              <span>备份配置</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧配置表单 -->
      <el-col :span="18">
        <el-card shadow="hover" class="config-content">
          <!-- 基础配置 -->
          <div v-show="activeMenu === 'basic'">
            <h3>基础配置</h3>
            <el-divider></el-divider>
            <el-form :model="configForm.basic" label-width="140px">
              <el-form-item label="系统名称">
                <el-input v-model="configForm.basic.systemName" placeholder="请输入系统名称"></el-input>
              </el-form-item>
              <el-form-item label="系统描述">
                <el-input type="textarea" v-model="configForm.basic.systemDesc" rows="3" placeholder="请输入系统描述"></el-input>
              </el-form-item>
              <el-form-item label="管理员邮箱">
                <el-input v-model="configForm.basic.adminEmail" placeholder="请输入管理员邮箱"></el-input>
              </el-form-item>
              <el-form-item label="页面标题">
                <el-input v-model="configForm.basic.pageTitle"></el-input>
              </el-form-item>
              <el-form-item label="分页大小">
                <el-input-number v-model="configForm.basic.pageSize" :min="5" :max="100" step-strictly></el-input-number>
              </el-form-item>
              <el-form-item label="日期格式">
                <el-select v-model="configForm.basic.dateFormat" style="width: 100%">
                  <el-option label="YYYY-MM-DD" value="YYYY-MM-DD"></el-option>
                  <el-option label="YYYY/MM/DD" value="YYYY/MM/DD"></el-option>
                  <el-option label="DD/MM/YYYY" value="DD/MM/YYYY"></el-option>
                  <el-option label="MM/DD/YYYY" value="MM/DD/YYYY"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间格式">
                <el-select v-model="configForm.basic.timeFormat" style="width: 100%">
                  <el-option label="HH:mm:ss" value="HH:mm:ss"></el-option>
                  <el-option label="HH:mm" value="HH:mm"></el-option>
                  <el-option label="hh:mm:ss a" value="hh:mm:ss a"></el-option>
                  <el-option label="hh:mm a" value="hh:mm a"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <!-- 模型配置 -->
          <div v-show="activeMenu === 'model'">
            <h3>模型配置</h3>
            <el-divider></el-divider>
            <el-form :model="configForm.model" label-width="140px">
              <el-form-item label="默认模型">
                <el-select v-model="configForm.model.defaultModel" style="width: 100%">
                  <el-option label="XGBoost模型" value="xgboost"></el-option>
                  <el-option label="随机森林模型" value="random_forest"></el-option>
                  <el-option label="逻辑回归模型" value="logistic"></el-option>
                  <el-option label="融合模型(推荐)" value="ensemble"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="模型更新周期">
                <el-select v-model="configForm.model.updateCycle" style="width: 100%">
                  <el-option label="每天" value="daily"></el-option>
                  <el-option label="每周" value="weekly"></el-option>
                  <el-option label="每月" value="monthly"></el-option>
                  <el-option label="手动更新" value="manual"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="自动优化">
                <el-switch v-model="configForm.model.autoOptimize"></el-switch>
              </el-form-item>
              <el-form-item label="特征工程配置">
                <el-input type="textarea" v-model="configForm.model.featureEngineering" rows="3" placeholder="JSON格式配置"></el-input>
              </el-form-item>
              <el-form-item label="训练集比例">
                <el-slider v-model="configForm.model.trainRatio" :format-tooltip="formatRatioTooltip" :step="0.05" :min="0.5" :max="0.9"></el-slider>
              </el-form-item>
              <el-form-item label="验证集比例">
                <el-slider v-model="configForm.model.validRatio" :format-tooltip="formatRatioTooltip" :step="0.05" :min="0" :max="0.3"></el-slider>
              </el-form-item>
            </el-form>
          </div>

          <!-- 预测配置 -->
          <div v-show="activeMenu === 'prediction'">
            <h3>预测配置</h3>
            <el-divider></el-divider>
            <el-form :model="configForm.prediction" label-width="140px">
              <el-form-item label="高风险阈值">
                <el-slider v-model="configForm.prediction.highRiskThreshold" :format-tooltip="formatThresholdTooltip" :step="0.05" :min="0.5" :max="1"></el-slider>
              </el-form-item>
              <el-form-item label="中风险阈值">
                <el-slider v-model="configForm.prediction.mediumRiskThreshold" :format-tooltip="formatThresholdTooltip" :step="0.05" :min="0.2" :max="0.5"></el-slider>
              </el-form-item>
              <el-form-item label="自动创建预警">
                <el-switch v-model="configForm.prediction.autoCreateAlert"></el-switch>
              </el-form-item>
              <el-form-item label="预警创建条件" v-if="configForm.prediction.autoCreateAlert">
                <el-select v-model="configForm.prediction.alertCondition" style="width: 100%">
                  <el-option label="仅高风险客户" value="high_only"></el-option>
                  <el-option label="高风险和中风险客户" value="high_medium"></el-option>
                  <el-option label="所有风险客户" value="all"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="批量预测限制">
                <el-input-number v-model="configForm.prediction.batchLimit" :min="100" :max="10000" :step="100"></el-input-number>
              </el-form-item>
              <el-form-item label="最小预测间隔(天)">
                <el-input-number v-model="configForm.prediction.minInterval" :min="1" :max="30"></el-input-number>
              </el-form-item>
              <el-form-item label="预测结果保存天数">
                <el-input-number v-model="configForm.prediction.resultRetention" :min="30" :max="365" :step="30"></el-input-number>
              </el-form-item>
            </el-form>
          </div>

          <!-- 通知配置 -->
          <div v-show="activeMenu === 'notification'">
            <h3>通知配置</h3>
            <el-divider></el-divider>
            <el-form :model="configForm.notification" label-width="140px">
              <el-form-item label="启用邮件通知">
                <el-switch v-model="configForm.notification.enableEmail"></el-switch>
              </el-form-item>
              <template v-if="configForm.notification.enableEmail">
                <el-form-item label="SMTP服务器">
                  <el-input v-model="configForm.notification.smtpServer"></el-input>
                </el-form-item>
                <el-form-item label="SMTP端口">
                  <el-input-number v-model="configForm.notification.smtpPort" :min="1" :max="65535"></el-input-number>
                </el-form-item>
                <el-form-item label="发件人邮箱">
                  <el-input v-model="configForm.notification.senderEmail"></el-input>
                </el-form-item>
                <el-form-item label="邮件密码">
                  <el-input v-model="configForm.notification.emailPassword" type="password" show-password></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="testEmailConnection">测试邮件连接</el-button>
                </el-form-item>
              </template>
              <el-form-item label="启用短信通知">
                <el-switch v-model="configForm.notification.enableSms"></el-switch>
              </el-form-item>
              <template v-if="configForm.notification.enableSms">
                <el-form-item label="短信API密钥">
                  <el-input v-model="configForm.notification.smsApiKey" show-password></el-input>
                </el-form-item>
                <el-form-item label="短信签名">
                  <el-input v-model="configForm.notification.smsSignature"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="testSmsConnection">测试短信连接</el-button>
                </el-form-item>
              </template>
              <el-form-item label="启用系统内通知">
                <el-switch v-model="configForm.notification.enableSystemNotification"></el-switch>
              </el-form-item>
              <el-form-item label="通知级别">
                <el-select v-model="configForm.notification.notificationLevel" style="width: 100%">
                  <el-option label="所有消息" value="all"></el-option>
                  <el-option label="重要消息" value="important"></el-option>
                  <el-option label="紧急消息" value="urgent"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <!-- 备份配置 -->
          <div v-show="activeMenu === 'backup'">
            <h3>备份配置</h3>
            <el-divider></el-divider>
            <el-form :model="configForm.backup" label-width="140px">
              <el-form-item label="自动备份">
                <el-switch v-model="configForm.backup.autoBackup"></el-switch>
              </el-form-item>
              <template v-if="configForm.backup.autoBackup">
                <el-form-item label="备份频率">
                  <el-select v-model="configForm.backup.backupFrequency" style="width: 100%">
                    <el-option label="每天" value="daily"></el-option>
                    <el-option label="每周" value="weekly"></el-option>
                    <el-option label="每月" value="monthly"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备份时间">
                  <el-time-picker v-model="configForm.backup.backupTime" format="HH:mm" style="width: 100%"></el-time-picker>
                </el-form-item>
                <el-form-item label="备份保留天数">
                  <el-input-number v-model="configForm.backup.retentionDays" :min="7" :max="365"></el-input-number>
                </el-form-item>
              </template>
              <el-form-item label="备份类型">
                <el-checkbox-group v-model="configForm.backup.backupTypes">
                  <el-checkbox label="database">数据库备份</el-checkbox>
                  <el-checkbox label="config">配置文件备份</el-checkbox>
                  <el-checkbox label="model">模型文件备份</el-checkbox>
                  <el-checkbox label="log">日志备份</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="备份路径">
                <el-input v-model="configForm.backup.backupPath"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="backupNow">立即备份</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作日志 -->
    <el-card shadow="hover" class="config-history">
      <template #header>
        <div class="card-header">
          <span>配置操作日志</span>
          <el-button size="small" type="primary" @click="refreshHistory">刷新</el-button>
        </div>
      </template>
      <el-table :data="configHistory" style="width: 100%">
        <el-table-column prop="time" label="时间" width="180"></el-table-column>
        <el-table-column prop="user" label="操作人" width="120"></el-table-column>
        <el-table-column prop="action" label="操作" width="120"></el-table-column>
        <el-table-column prop="section" label="配置区域" width="120"></el-table-column>
        <el-table-column prop="details" label="详细信息"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllConfigs, batchUpdateConfigs, resetDefaultConfigs } from '@/api/modules/system'

// 当前选中的菜单项
const activeMenu = ref('basic')



// 配置表单数据
const configForm = reactive({
  basic: {
    systemName: '电信客户流失预警系统',
    systemDesc: '基于机器学习的电信客户流失预测与预警管理系统',
    adminEmail: 'admin@example.com',
    pageTitle: '电信客户流失预警系统',
    pageSize: 10,
    dateFormat: 'YYYY-MM-DD',
    timeFormat: 'HH:mm:ss'
  },
  model: {
    defaultModel: 'ensemble',
    updateCycle: 'weekly',
    autoOptimize: true,
    featureEngineering: JSON.stringify({
      "scaling": true,
      "encoding": "one-hot",
      "feature_selection": true
    }, null, 2),
    trainRatio: 0.7,
    validRatio: 0.15
  },
  prediction: {
    highRiskThreshold: 0.7,
    mediumRiskThreshold: 0.4,
    autoCreateAlert: true,
    alertCondition: 'high_medium',
    batchLimit: 1000,
    minInterval: 7,
    resultRetention: 90
  },
  notification: {
    enableEmail: true,
    smtpServer: 'smtp.example.com',
    smtpPort: 587,
    senderEmail: 'notification@example.com',
    emailPassword: 'password123',
    enableSms: false,
    smsApiKey: '',
    smsSignature: '电信客户服务',
    enableSystemNotification: true,
    notificationLevel: 'important'
  },
  backup: {
    autoBackup: true,
    backupFrequency: 'daily',
    backupTime: new Date(2023, 0, 1, 3, 0), // 凌晨3点
    retentionDays: 30,
    backupTypes: ['database', 'config', 'model'],
    backupPath: '/backup'
  }
})

// 配置历史记录
const configHistory = ref([
  {
    time: '2023-06-10 15:23:45',
    user: '管理员',
    action: '修改',
    section: '基础配置',
    details: '修改了系统名称和描述'
  },
  {
    time: '2023-06-05 09:14:32',
    user: '管理员',
    action: '修改',
    section: '预测配置',
    details: '调整了风险阈值设置'
  },
  {
    time: '2023-06-01 14:05:18',
    user: '系统',
    action: '初始化',
    section: '全部配置',
    details: '系统初始化默认配置'
  }
])

// 处理菜单选择
const handleMenuSelect = (key) => {
  activeMenu.value = key
}

// 格式化比例提示
const formatRatioTooltip = (val) => {
  return val * 100 + '%'
}

// 格式化阈值提示
const formatThresholdTooltip = (val) => {
  return val * 100 + '%'
}

// 保存配置
const saveConfig = async () => {
  try {
    // 简单验证基础配置
    if (!configForm.basic.systemName || !configForm.basic.systemName.trim()) {
      ElMessage.error('系统名称不能为空')
      activeMenu.value = 'basic'
      return
    }

    if (!configForm.basic.adminEmail || !configForm.basic.adminEmail.trim()) {
      ElMessage.error('管理员邮箱不能为空')
      activeMenu.value = 'basic'
      return
    }

    // 构建要保存的配置数据（保存所有配置）
    const configsToSave = {}

    // 基础配置
    Object.keys(configForm.basic).forEach(key => {
      configsToSave[`system_${key.toLowerCase()}`] = configForm.basic[key]
    })

    // 模型配置
    Object.keys(configForm.model).forEach(key => {
      let value = configForm.model[key]
      // 特殊处理时间类型
      if (key === 'backupTime' && value instanceof Date) {
        value = value.toTimeString().slice(0, 5) // HH:mm格式
      }
      configsToSave[`model_${key.toLowerCase()}`] = value
    })

    // 预测配置
    Object.keys(configForm.prediction).forEach(key => {
      configsToSave[`prediction_${key.toLowerCase()}`] = configForm.prediction[key]
    })

    // 通知配置
    Object.keys(configForm.notification).forEach(key => {
      configsToSave[`notification_${key.toLowerCase()}`] = configForm.notification[key]
    })

    // 备份配置
    Object.keys(configForm.backup).forEach(key => {
      let value = configForm.backup[key]
      // 特殊处理时间类型
      if (key === 'backupTime' && value instanceof Date) {
        value = value.toTimeString().slice(0, 5) // HH:mm格式
      }
      configsToSave[`backup_${key.toLowerCase()}`] = value
    })

    // 调用API保存配置
    const response = await batchUpdateConfigs(configsToSave)

    if (response.success) {
      ElMessage({
        message: '配置保存成功',
        type: 'success'
      })

      // 添加配置历史
      const now = new Date()
      const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

      configHistory.value.unshift({
        time: timeStr,
        user: '管理员',
        action: '保存',
        section: getMenuTitle(activeMenu.value),
        details: `保存${getMenuTitle(activeMenu.value)}配置`
      })
    } else {
      ElMessage.error(response.error || '保存配置失败')
    }
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  }
}

// 重置配置
const resetConfig = async () => {
  try {
    await ElMessageBox.confirm('确定要重置当前配置吗？这将恢复为默认设置。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用API重置为默认配置
    const response = await resetDefaultConfigs()

    if (response.success) {
      // 重新加载配置
      await loadConfigs()

      ElMessage({
        message: '配置已重置为默认值',
        type: 'success'
      })
    } else {
      ElMessage.error(response.error || '重置配置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置配置失败:', error)
      ElMessage.error('重置配置失败')
    }
  }
}

// 刷新历史记录
const refreshHistory = () => {
  // 在真实环境中这里会调用API获取最新的配置历史
  ElMessage({
    message: '历史记录已刷新',
    type: 'success'
  })
}

// 立即备份
const backupNow = async () => {
  try {
    ElMessage({
      message: '正在执行备份...',
      type: 'info'
    })

    // 模拟备份过程
    await new Promise(resolve => setTimeout(resolve, 2000))

    ElMessage({
      message: '备份完成',
      type: 'success'
    })

    // 添加备份历史记录
    const now = new Date()
    const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

    configHistory.value.unshift({
      time: timeStr,
      user: '管理员',
      action: '备份',
      section: '系统备份',
      details: '手动执行系统备份'
    })
  } catch (error) {
    console.error('备份失败:', error)
    ElMessage.error('备份失败')
  }
}

// 测试邮件连接
const testEmailConnection = async () => {
  try {
    ElMessage({
      message: '正在测试邮件连接...',
      type: 'info'
    })

    // 模拟测试过程
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage({
      message: '邮件连接测试成功',
      type: 'success'
    })
  } catch (error) {
    console.error('邮件连接测试失败:', error)
    ElMessage.error('邮件连接测试失败')
  }
}

// 测试短信连接
const testSmsConnection = async () => {
  try {
    ElMessage({
      message: '正在测试短信连接...',
      type: 'info'
    })

    // 模拟测试过程
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage({
      message: '短信连接测试成功',
      type: 'success'
    })
  } catch (error) {
    console.error('短信连接测试失败:', error)
    ElMessage.error('短信连接测试失败')
  }
}

// 导出配置
const exportConfig = () => {
  try {
    const configData = {
      basic: configForm.basic,
      model: configForm.model,
      prediction: configForm.prediction,
      notification: configForm.notification,
      backup: configForm.backup,
      exportTime: new Date().toISOString(),
      version: '1.0.0'
    }

    const dataStr = JSON.stringify(configData, null, 2)
    const blob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = `system-config-${new Date().toISOString().split('T')[0]}.json`
    link.style.display = 'none'

    try {
      document.body.appendChild(link)
      link.click()
    } finally {
      // 确保清理操作在try-finally中执行
      setTimeout(() => {
        try {
          if (link.parentNode) {
            document.body.removeChild(link)
          }
          URL.revokeObjectURL(url)
        } catch (cleanupError) {
          console.warn('清理下载链接失败:', cleanupError)
        }
      }, 100)
    }

    ElMessage.success('配置导出成功')
  } catch (error) {
    console.error('导出配置失败:', error)
    ElMessage.error('导出配置失败')
  }
}

// 导入配置
const importConfig = () => {
  try {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.json'
    input.style.display = 'none'

    input.onchange = (event) => {
      const file = event.target.files[0]
      if (!file) return

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const configData = JSON.parse(e.target.result)

          // 验证配置数据格式
          if (!configData.basic || !configData.model || !configData.prediction) {
            ElMessage.error('配置文件格式不正确')
            return
          }

          ElMessageBox.confirm('确定要导入配置吗？这将覆盖当前配置。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 导入配置
            Object.assign(configForm.basic, configData.basic)
            Object.assign(configForm.model, configData.model)
            Object.assign(configForm.prediction, configData.prediction)
            Object.assign(configForm.notification, configData.notification)
            Object.assign(configForm.backup, configData.backup)

            ElMessage.success('配置导入成功')
          }).catch(() => {})
        } catch (error) {
          console.error('解析配置文件失败:', error)
          ElMessage.error('配置文件格式错误')
        }
      }

      reader.onerror = () => {
        ElMessage.error('文件读取失败')
      }

      reader.readAsText(file)
    }

    // 添加到DOM并触发点击
    document.body.appendChild(input)
    input.click()

    // 清理
    setTimeout(() => {
      try {
        if (input.parentNode) {
          document.body.removeChild(input)
        }
      } catch (cleanupError) {
        console.warn('清理文件输入元素失败:', cleanupError)
      }
    }, 100)

  } catch (error) {
    console.error('创建文件输入失败:', error)
    ElMessage.error('导入功能初始化失败')
  }
}

// 获取菜单标题
const getMenuTitle = (menu) => {
  const menuMap = {
    'basic': '基础配置',
    'model': '模型配置',
    'prediction': '预测配置',
    'notification': '通知配置',
    'backup': '备份配置'
  }
  return menuMap[menu] || '系统配置'
}

// 加载配置
const loadConfigs = async () => {
  try {
    const response = await getAllConfigs()

    if (response && response.success && response.data) {
      const configs = response.data

      // 解析基础配置
      configForm.basic = {
        systemName: configs.system_name || '电信客户流失预警系统',
        systemDesc: configs.system_desc || '基于机器学习的电信客户流失预测与预警管理系统',
        adminEmail: configs.system_adminemail || 'admin@example.com',
        pageTitle: configs.system_pagetitle || '电信客户流失预警系统',
        pageSize: configs.system_pagesize || 10,
        dateFormat: configs.system_dateformat || 'YYYY-MM-DD',
        timeFormat: configs.system_timeformat || 'HH:mm:ss'
      }

      // 解析模型配置
      configForm.model = {
        defaultModel: configs.model_defaultmodel || 'ensemble',
        updateCycle: configs.model_updatecycle || 'weekly',
        autoOptimize: configs.model_autooptimize || true,
        featureEngineering: configs.model_featureengineering || JSON.stringify({
          "scaling": true,
          "encoding": "one-hot",
          "feature_selection": true
        }, null, 2),
        trainRatio: configs.model_trainratio || 0.7,
        validRatio: configs.model_validratio || 0.15
      }

      // 解析预测配置
      configForm.prediction = {
        highRiskThreshold: configs.prediction_highriskthreshold || 0.7,
        mediumRiskThreshold: configs.prediction_mediumriskthreshold || 0.4,
        autoCreateAlert: configs.prediction_autocreatealert || true,
        alertCondition: configs.prediction_alertcondition || 'high_medium',
        batchLimit: configs.prediction_batchlimit || 1000,
        minInterval: configs.prediction_mininterval || 7,
        resultRetention: configs.prediction_resultretention || 90
      }

      // 解析通知配置
      configForm.notification = {
        enableEmail: configs.notification_enableemail || true,
        smtpServer: configs.notification_smtpserver || 'smtp.example.com',
        smtpPort: configs.notification_smtpport || 587,
        senderEmail: configs.notification_senderemail || 'notification@example.com',
        emailPassword: configs.notification_emailpassword || '',
        enableSms: configs.notification_enablesms || false,
        smsApiKey: configs.notification_smsapikey || '',
        smsSignature: configs.notification_smssignature || '电信客户服务',
        enableSystemNotification: configs.notification_enablesystemnotification || true,
        notificationLevel: configs.notification_notificationlevel || 'important'
      }

      // 解析备份配置
      configForm.backup = {
        autoBackup: configs.backup_autobackup || true,
        backupFrequency: configs.backup_backupfrequency || 'daily',
        backupTime: configs.backup_backuptime ? new Date(configs.backup_backuptime) : new Date(2023, 0, 1, 3, 0),
        retentionDays: configs.backup_retentiondays || 30,
        backupTypes: configs.backup_backuptypes || ['database', 'config', 'model'],
        backupPath: configs.backup_backuppath || '/backup'
      }
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    ElMessage.error('加载配置失败')
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    await loadConfigs()
  } catch (error) {
    console.error('初始化配置页面失败:', error)
    // 即使加载配置失败，也要显示页面，使用默认配置
  }
})


</script>

<style lang="scss" scoped>
.system-config-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .config-nav {
    margin-bottom: 20px;
    
    .config-menu {
      border-right: none;
    }
  }
  
  .config-content {
    margin-bottom: 20px;
    min-height: 500px;
    
    h3 {
      margin-top: 0;
      color: #303133;
      font-weight: 500;
    }
  }
  
  .config-history {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  @media (max-width: 768px) {
    .config-nav {
      margin-bottom: 20px;
    }
  }
}
</style> 